<template>
  <div class="app-container">
    <!-- 查询 -->
    <tl-list-search ref="search" :query-param="queryParam" @search="doQuery" :isDisplayDefaultSearch="false" :isDisplaySearch="false" v-if="isHeaderDisplay">
      <template slot="search">
        <el-form-item prop="code" v-if="editFlag">
          <label>项目</label>
          <el-input v-model="queryParam.qry_projectname" :disabled="true" class="tl-ref-selector" style="width:200px">
            <el-button slot="append" type="primary" icon="el-icon-search" @click="openpmProjectRefDialog"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <label>财务期间月份</label>
          <el-date-picker v-model="queryParam.qry_month" type="month" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="doQuery">搜索</el-button>
        <el-button class="filter-item" type="primary" icon="el-icon-refresh-right" @click="resetQueryParam" v-if="editFlag">重置</el-button>
      </template>
    </tl-list-search>
    <!-- 工具栏 -->
    <tl-list-toolbar ref="toolbar" :isDisplayAdd="false" @add="openAddDialog('editForm')" @exportExcel="doExportExcel" :isDisplayDeleteBatch="false" @deleteBatch="doDeleteBatch" @refresh="doRefresh" @columnCustomize="doColumnCustomize" @displaySearch="doDisplaySearch" :disableDeleteBatch="selectedRowKeys.length <= 0">
      <template slot="left-btn"> </template>
    </tl-list-toolbar>
    <div>
      <!-- 列表选择 -->
      <div class="table-alert-div" ref="selector">
        <el-alert type="success" :closable="false" class="tl-table-alert-info" effect="light">
          <template slot="title">
            已选择&nbsp;<a class="tl-table-alert-info-a1">{{ selectedRowKeys.length }}</a>项&nbsp;&nbsp;
            <a class="tl-table-alert-info-a2" @click="doClearSelected">全部清空</a>
          </template>
        </el-alert>
      </div>
      <!--表格渲染-->
      <el-table class="tl-table" ref="mainTable" :height="tableHeight" resizable-key="tableHeight" :resizable-refs="tableResizeRefs" v-loading="loading" :data="datas" @selection-change="doSelectChange" @sort-change="doSortChange" @row-dblclick="doRowDbClick" row-key="id" border fit :row-class-name="doChangeRowClassName">
        <!-- <el-table-column type="selection" width="40px" fixed="left" :selectable="doDisableCheckBox"></el-table-column> -->
        <el-table-column type="index" label="序号" width="55px" align="center"></el-table-column>
        <el-table-column v-if="editFlag" prop="dispprojectid" label="所属项目" width="250px" sortable="custom" sort-by="projectname" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="projectcode" label="项目编号" width="150px" sortable="custom" sort-by="projectcode" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="financialmonth" label="财务期间月份" width="170px" sortable="custom" sort-by="financialmonth" align="center" header-align="center" :formatter="monthFormat" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="cost" label="月成本" width="150px" sortable="custom" sort-by="cost" align="right" :formatter="moneyFormat" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="confirmincome" label="确认收入" width="150px" sortable="custom" sort-by="confirmincome" align="right" :formatter="moneyFormat" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="dispchecked" label="确认" width="100px" sortable="custom" sort-by="checked" align="center" header-align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.checked === 1" type="success">是</el-tag>
            <el-tag v-else type="danger">否</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="costwages" label="月成本-工资" width="150px" sortable="custom" sort-by="costwages" align="right" :formatter="moneyFormat" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="costtravel" label="月成本-差旅" width="150px" sortable="custom" sort-by="costtravel" align="right" :formatter="moneyFormat" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="costexpenses" label="月成本费用" width="150px" sortable="custom" sort-by="costexpenses" align="right" :formatter="moneyFormat" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="costcars" label="月成本车辆" width="150px" sortable="custom" sort-by="costcars" align="right" :formatter="moneyFormat" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="costothers" label="月成本其他" width="150px" sortable="custom" sort-by="costothers" align="right" :formatter="moneyFormat" header-align="center" :show-overflow-tooltip="true"></el-table-column> -->
        <el-table-column prop="costexplain" label="成本说明" width="150px" sortable="custom" sort-by="costexplain" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="incomeexplain" label="收入备注" width="150px" sortable="custom" sort-by="incomeexplain" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <!-- <el-table-column prop="orgname" label="经办公司" width="250px" sortable="custom" sort-by="orgname" align="left" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="orgcode" label="经办公司编码" width="120px" sortable="custom" sort-by="orgcode" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column> -->
        <el-table-column prop="deptname" label="经办部门" width="250px" sortable="custom" sort-by="deptname" align="left" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="deptcode" label="经办部门编码" width="120px" sortable="custom" sort-by="deptcode" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="username" label="经办人姓名" width="120px" sortable="custom" sort-by="username" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="usercode" label="经办人工号" width="120px" sortable="custom" sort-by="usercode" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="description" label="备注" min-width="250px" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <!-- <el-table-column prop="extendfield1" label="扩展1" width="150px" sortable="custom" sort-by="extendfield1" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="extendfield2" label="扩展2" width="150px" sortable="custom" sort-by="extendfield2" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="extendfield3" label="扩展3" width="150px" sortable="custom" sort-by="extendfield3" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="extendfield4" label="扩展4" width="150px" sortable="custom" sort-by="extendfield4" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="extendfield5" label="扩展5" width="150px" sortable="custom" sort-by="extendfield5" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="extendfield6" label="扩展6" width="150px" sortable="custom" sort-by="extendfield6" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="extendfield7" label="扩展7" width="150px" sortable="custom" sort-by="extendfield7" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="extendfield8" label="扩展8" width="150px" sortable="custom" sort-by="extendfield8" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="extendfield9" label="扩展9" width="150px" sortable="custom" sort-by="extendfield9" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="extendfield10" label="扩展10" width="150px" sortable="custom" sort-by="extendfield10" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column> -->
        <!-- <el-table-column label="操作" width="220px" v-slot="scope" fixed="right">
          <el-button type="text" icon="el-icon-edit" @click="openEditDialog('editForm', scope.row.id)" :disabled="!editFlag || scope.row.checked === 1">编辑</el-button>
          <el-button type="text" icon="el-icon-delete" @click="doDelete(scope.row.id)" :disabled="!editFlag || scope.row.checked === 1">删除</el-button>
          <el-dropdown trigger="hover">
            <el-button type="text" icon="el-icon-s-operation" style="margin-left:10px">更多<i class="el-icon-arrow-down el-icon--right"></i></el-button>
            <el-dropdown-menu>
              <el-dropdown-item icon="el-icon-view" @click.native="openViewDialog('editForm', scope.row.id)">查看</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-table-column> -->
        <el-table-column label="操作" width="100px" v-slot="scope" fixed="right">
          <el-dropdown trigger="hover">
            <el-button type="text" icon="el-icon-s-operation" style="margin-left:10px">操作<i class="el-icon-arrow-down el-icon--right"></i></el-button>
            <el-dropdown-menu>
              <el-dropdown-item icon="el-icon-edit" @click.native="openEditDialog('editForm', scope.row.id)" :disabled="!editFlag || scope.row.checked === 1">编辑</el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" :disabled="!editFlag || scope.row.checked === 1" @click.native="doDelete(scope.row.id)">删除</el-dropdown-item>
              <el-dropdown-item icon="el-icon-refresh-left" :disabled="!editFlag || scope.row.checked !== 1" @click.native="cancelConfirm(scope.row.id)">取消确认</el-dropdown-item>
              <el-dropdown-item icon="el-icon-view" @click.native="openViewDialog('editForm', scope.row.id)">查看</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-table-column>
      </el-table>
      <!-- 列表分页 -->
      <el-row class="pagebar" ref="pager">
        <el-pagination @size-change="doChangeSize" @current-change="doChangeIndex" :current-page="pageInfo.currentPage" :page-sizes="pageInfo.pageSizes" :total="pageInfo.totalCount" layout="total, sizes, prev, pager, next, jumper" background class="tl-table-pagination"> </el-pagination>
      </el-row>
      <tl-edit ref="editForm" @refresh="doRefresh" :projectId="projectId" :editFlag="editFlag"></tl-edit>
      <tlpm-project-ref ref="pmProjectRef" @confirm="getpmProjectRefData" :isSingleSelect="true"></tlpm-project-ref>
    </div>
  </div>
</template>

<script>
/** mixins */
import { mixin_list } from "@tapui/mixins/mixin_list"
/** 子组件 */
import tlEdit from "./edit"
import tlpmProjectRef from "@/views/ProjectManage/pmProject/highestAuthorityRefList"
/** 工具类 */
import { getAction, putAction, postAction, deleteAction } from "@tapui/utils/http"
import { formatDate } from "@tapui/utils/date"
import { rmbFormat } from "../../../utils/calculation"
import { exportExcelAxio } from "@tapui/api/office"
const baseUrl = process.env.BASE_API

export default {
  name: "pmCostIncomeQuery",
  mixins: [mixin_list],
  components: { tlEdit, tlpmProjectRef },
  data() {
    return {
      description: "项目财务成本与确认收入-列表查询",
      urlPrefix: "/pm/costIncome/",
      url: {
        // queryCodeList: '/pm/costIncome/dataCodeList'
        confirmCostIncomes: "/pm/costIncome/confirm",
        cancelConfirm: "/pm/costIncome/cancelConfirm",
        generateCostIncomes: "/pm/costIncome/generate",
        downloadTemplate: "/pm/costIncome/downloadTemplate",
        import: "/pm/costIncome/importExcel"
      },
      // 排序参数
      sorterInfo: {
        sidx: "PmCostIncome.createon",
        sord: "desc"
      },
      queryParam: {
        qry_projectid: this.projectId
      },
      // 当前页面的编辑状态
      editFlag: true,
      reduceHeight: 325
    }
  },
  props: {
    projectId: {
      type: [Number, String],
      default: function() {
        return ""
      }
    },
    // 模块是否可以编辑
    moduleEditFlag: {
      type: Number,
      default: function() {
        return 1
      }
    },
    // 当前登录人角色 PM--项目经理 PP--项目参数人 OTHER--其他
    currentRole: {
      type: String,
      default: function() {
        return "PM"
      }
    }
  },
  methods: {
    // 禁用表格前面的选择
    doDisableCheckBox(row, index) {
      if (row.checked === 1) {
        return false
      } else {
        return true
      }
    },
    /** 打开项目参照 */
    openpmProjectRefDialog() {
      this.$refs.pmProjectRef.visible = true
    },
    /** 获取项目参数数据 */
    getpmProjectRefData(selectionRow, selectKey, selectionValue) {
      const { id, name } = selectionRow
      this.$set(this.queryParam, "qry_projectid", id)
      this.$set(this.queryParam, "qry_projectname", name)
    },
    resetQueryParam() {
      this.queryParam = {}
    },
    // 格式化日期 yyyy-MM
    monthFormat(row, column, cellValue, index) {
      let dateValue = row[column.property]
      if (dateValue && dateValue.length > 0) {
        return formatDate(new Date(dateValue), "yyyy-MM")
      } else {
        return ""
      }
    },
    moneyFormat(row, column, cellValue, index) {
      return rmbFormat(row[column.property])
    },
    doRowDbClick(row, column, event) {
      if (this.editFlag && row.checked === 0) {
        this.rowDbClickActionType = "edit"
      } else {
        this.rowDbClickActionType = "view"
      }
      if (this.rowDbClickActionType === "edit") {
        this.openEditDialog("editForm", row.id)
      } else if (this.rowDbClickActionType === "view") {
        this.openViewDialog("editForm", row.id)
      }
    },
    initParam() {
      this.editFlag = this.moduleEditFlag === 1 && this.currentRole === "PM"
      this.reduceHeight = this.editFlag ? 134 : 325
    },
    searchList(projectId) {
      if (!this.editFlag) {
        this.queryParam.qry_projectid = projectId
        this.loadData({})
      }
    },
    confirmCostIncomes() {
      if (!this.url.confirmCostIncomes) {
        this.$tap.alert("请设置confirmCostIncomes地址!", "warning")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$tap.alert("请选择记录！", "warning")
        return
      } else {
        var ids = ""
        for (var index = 0; index < this.selectedRowKeys.length; index++) {
          if (index === this.selectedRowKeys.length - 1) {
            ids += this.selectedRowKeys[index]
          } else {
            ids += this.selectedRowKeys[index] + ","
          }
        }
        putAction(this.url.confirmCostIncomes, { ids: ids }).then((res) => {
          if (res.success) {
            this.$tap.message(res.message, "success")
            this.loadData({})
          } else {
            this.$tap.alert(res.message, "warning")
          }
        })
      }
    },
    cancelConfirm(id) {
      this.saveLoading = true
      putAction(this.url.cancelConfirm, { id })
        .then((res) => {
          if (res.success) {
            this.$tap.message(res.message, "success")
            this.loadData({})
          } else {
            this.$tap.alert(res.message, "warning")
          }
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    generateCostIncomes() {
      this.saveLoading = true
      postAction(this.url.generateCostIncomes)
        .then((res) => {
          if (res.success) {
            this.$tap.message(res.message, "success")
            this.loadData({})
          } else {
            this.$tap.alert(res.message, "warning")
          }
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    /** 导出Excel*/
    doExportExcel() {
      if (!this.beforeExportData()) return
      let cols = []
      this.$refs.mainTable.$children.forEach((col) => {
        if (col.$options._componentTag === 'el-table-column') {
          if (col.$options.propsData.prop) {
            cols.push(col.$options.propsData.prop + ';' + col.$options.propsData.label)
          }
        }
      })
      let url = baseUrl + `${this.url.exportExcel}`
      let data = {}
      Object.assign(data, this.getQueryParams(), { cols: cols.join(',') })
      exportExcelAxio({ url: url, data: data })
        .then((res) => {
          var reader = new FileReader()
          reader.readAsText(res.data, 'utf-8')
          reader.onload = () => {
            try {
              var info = JSON.parse(reader.result)
              this.$tap.alert(info.message)
            } catch (e) {
              var isTaskExport = res.headers.istaskexport
              if (isTaskExport === '1') {
                this.$tap.alert('系统正在导出，请到excel导出任务页面下载')
              } else {
                var blob = new Blob([res.data], { type: 'application/octet-stream;charset=utf-8' })
                var filename = '导出数据.xlsx'
                if (typeof filename === 'undefined') {
                  filename = '导出数据.xlsx'
                }
                var tempObjectUrl = window.URL.createObjectURL(blob)
                var aLink = document.createElement('a')
                aLink.style.display = 'none'
                aLink.download = filename
                aLink.href = tempObjectUrl
                document.body.appendChild(aLink)
                aLink.click()
                document.body.removeChild(aLink)
                window.URL.revokeObjectURL(tempObjectUrl)
                this.afterExportData()
              }
            }
          }
        })
        .catch((error) => {
          this.$tap.alert(error, 'warning')
        })
    },
    downloadTemplate() {
      const url = process.env.BASE_API + `${this.url.downloadTemplate}`
      const param = {
        url,
        data: {}
      }
      exportExcelAxio(param)
        .then((res) => {
          var reader = new FileReader()
          reader.readAsText(res.data, "utf-8")
          reader.onload = () => {
            try {
              var info = JSON.parse(reader.result)
              this.$tap.alert(info.message)
            } catch (e) {
              var isTaskExport = res.headers.istaskexport
              if (isTaskExport === "1") {
                this.$tap.alert("系统正在导出，请到excel导出任务页面下载")
              } else {
                debugger
                var blob = new Blob([res.data], { type: "application/octet-stream;charset=utf-8" })
                var filename = decodeURI(res.headers['filename'])
                if (typeof filename === "undefined") {
                  filename = "财务确认与收入模板.xlsx"
                }
                var tempObjectUrl = window.URL.createObjectURL(blob)
                var aLink = document.createElement("a")
                aLink.style.display = "none"
                aLink.download = filename
                aLink.href = tempObjectUrl
                document.body.appendChild(aLink)
                aLink.click()
                document.body.removeChild(aLink)
                window.URL.revokeObjectURL(tempObjectUrl)
              }
            }
          }
        })
        .catch((error) => {
          this.$tap.alert(error, "warning")
        })
    }
  },
  watch: {
    projectId(newValue, oldValue) {
      this.searchList(newValue)
    }
  },
  mounted() {
    this.initParam()
  }
}
</script>

<style scoped></style>
